package com.winchain.chainbill.bill.biz.discount.service.impl;

import com.shell.bee.base.exception.UnCheckMsgException;
import com.shell.framework.utils.CommonDataUtil;
import com.winchain.chainbill.bill.base.po.CbDct;
import com.winchain.chainbill.bill.base.service.CbDctService;
import com.winchain.chainbill.bill.biz.Bill;
import com.winchain.chainbill.bill.biz.BillTranEvent;
import com.winchain.chainbill.bill.biz.discount.service.BillDctEventService;
import com.winchain.chainbill.bill.biz.discount.vo.BillDct;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("billDctEventService")
public class BillDctEventServiceImpl implements BillDctEventService {
	@Autowired
	private CbDctService CbDctService;

	public BillTranEvent<CbDct> getBillTranEvent(String billId, boolean callback) {
		List<BillDct> bills = this.CbDctService.selectBillDctsByBillIdAndState(billId, "1");
		if ((bills == null) || (bills.size() == 0)) {
			throw new UnCheckMsgException("������������������������");
		}
		Bill<CbDct> prntBill = new Bill();

		String dctDate = null;
		List<Bill<CbDct>> children = new ArrayList();
		for (BillDct billDct : bills) {
			if (billId.equals(billDct.getPrntId())) {
				Bill<CbDct> childBill = new Bill();
				if (billDct.getDctId() == null) {
					billDct.setOptSeq(billDct.getCbOptSeq());
				} else {
					dctDate = billDct.getDctDate();
				}
				childBill.setRec(billDct.getRec());
				childBill.setSource(billDct.getDct());

				children.add(childBill);
			} else {
				if (billDct.getDctId() == null) {
					billDct.setOptSeq(billDct.getCbOptSeq());
					if (!callback) {
						billDct.setBuyerId(CommonDataUtil.getCurEntId());
						billDct.setBuyerNm(CommonDataUtil.getCurEntName());
					}
				} else {
					dctDate = billDct.getDctDate();
				}
				if (callback) {
					billDct.setDctDate(dctDate);
				}
				prntBill.setRec(billDct.getRec());
				prntBill.setSource(billDct.getDct());
			}
		}
		Object event = new BillTranEvent(prntBill);
		((BillTranEvent) event).setChildren(children);

		return (BillTranEvent<CbDct>) event;
	}
}
